package Tree;

public class _450_DeleteNodeinaBST {
    public TreeNode deleteNode(TreeNode root, int key) {
        return remove(root,key);
    }

    public TreeNode remove(TreeNode root,int key) {
        if (root != null) {
            if (root.val > key) {
                root.left = remove(root.left,key);
            } else if (root.val < key) {
                root.right = remove(root.right,key);
            } else {
                if (root.left != null && root.right != null) {
                    TreeNode tp = findMin(root.right);
                    root.val = tp.val;
                    root.right = remove(root.right,tp.val);
                } else {
                    //contains the 3 situations:has left node,right node and has no subnode.
                    root = (root.left != null) ? root.left : root.right;
                }
            }
        }
        return root;
    }

    public TreeNode findMin(TreeNode root) {
        if (root == null) {
            return root;
        } else if (root.left == null) {
            return root;
        }
        return findMin(root.left);
    }

}
